package com.jin.controller;

import com.jin.common.Result;
import com.jin.service.CommonService;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@Slf4j
@RestController
@RequestMapping("/api/common")
public class CommonController {

    @Resource
    private CommonService commonService;

    /**
     * 上传文件
     */
    @PostMapping("/upload")
    @Operation(summary = "上传文件", description = "上传文件到OSS")
    public Result<String> uploadFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return new Result<>(500, null, "上传文件不能为空");
        }

        try {
            String fileUrl = commonService.uploadFile(file);
            return Result.success(fileUrl);
        } catch (Exception e) {
            log.error("文件上传失败: ", e);
            return new Result<>(500, null, "文件上传失败：" + e.getMessage());
        }
    }

    /**
     * 上传图片
     */
    @PostMapping("/upload/image")
    @Operation(summary = "上传图片", description = "上传图片到OSS（包含格式校验）")
    public Result<String> uploadImage(@RequestParam("image") MultipartFile file) {
        if (file.isEmpty()) {
            return new Result<>(500, null, "上传图片不能为空");
        }

        try {
            String fileUrl = commonService.uploadImage(file);
            return Result.success(fileUrl);
        } catch (Exception e) {
            log.error("图片上传失败: ", e);
            return new Result<>(500, null, "图片上传失败：" + e.getMessage());
        }
    }

    /**
     * 删除文件
     */
    @DeleteMapping("/file")
    @Operation(summary = "删除文件", description = "从OSS删除文件")
    public Result<Boolean> deleteFile(@RequestParam("fileUrl") String fileUrl) {
        try {
            boolean result = commonService.deleteFile(fileUrl);
            if (result) {
                return Result.success(Boolean.TRUE);
            } else {
                return Result.error("文件删除失败");
            }
        } catch (Exception e) {
            log.error("文件删除失败: ", e);
            return Result.error("文件删除失败：" + e.getMessage());
        }
    }
}
